package com.new_blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.new_blog.common.AppVarible;
import com.new_blog.common.PasswordUtils;
import com.new_blog.common.ResultAjax;
import com.new_blog.common.SessionUtils;
import com.new_blog.mapper.UserinfoMapper;
import com.new_blog.model.ImageUtil;
import com.new_blog.model.Userinfo;
import com.new_blog.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Random;
import java.util.Optional;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TQ02
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/userinfo")
public class UserinfoController {
    @Autowired
    private UserinfoService userService;
    @Autowired
    private UserinfoMapper userMapper;


    @Autowired
    ImageUtil imageUtil;

    //注册
    @PostMapping("/reg")
    public ResultAjax reg(Userinfo user){
        Random random=new Random();
        String str=new String();
        if(user==null || !StringUtils.hasLength(user.getUname())
                || !StringUtils.hasLength(user.getPassword())){
            return ResultAjax.fail(-1,"注册信息错误");
        }
        if(user.getPassword().length()<5){
            return ResultAjax.fail(-1,"非法注册");
        }
        while(true){
            char[] array={'0','1','2','3','4','5','6','7','8','9',
                    'A','B','C','D','E','F','G','H','I','J','K','L','M',
                    'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

            for(int i=0;i<9;i++){
                int k;
                if(i<3){
                    k=random.nextInt(25)+10;
                }else{
                    k= random.nextInt(10);
                }
                str+=String.valueOf(array[k]);
            }
            Userinfo u1 = userMapper.selectOne(new QueryWrapper<Userinfo>().eq("uId", str));
            if(u1==null){
                break;
            }
        }
        String oldPassword=user.getPassword();
        String newPassword= PasswordUtils.encrypt(oldPassword);
        user.setPassword(newPassword);
        user.setUid(str);
        if (userService.save(user)) {
            user.setPassword(oldPassword);
            return ResultAjax.succ(user);
        }
        return ResultAjax.fail(-1,"注册失败");
    }
    //验证码
    @RequestMapping("/generateImage")
    public void generateImage(HttpServletRequest req, HttpServletResponse res){
        imageUtil.init();
        //验证码文字
        final String verifyCode=imageUtil.getStr();
        //验证码图片
        final ByteArrayInputStream image=imageUtil.getImage();
        res.setContentType("image/jpeg");
        //将文章存储在session当中
        HttpSession session= req.getSession();
        session.setAttribute("abc",verifyCode);

        byte[] bytes=new byte[1024];
        try(final ServletOutputStream out=res.getOutputStream()){
            while(image.read(bytes)!=-1){
                out.write(bytes);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //登陆
    @PostMapping("/login")
    public ResultAjax login(Userinfo user, HttpServletRequest req,String password2) {
        if (user == null || !StringUtils.hasLength(user.getUid())
                || !StringUtils.hasLength(user.getPassword()))
            return ResultAjax.fail(-1, "非法");
        if(!password2.equals(req.getSession().getAttribute("abc").toString())){
            return ResultAjax.fail(2, "验证码错误");
        }
        Userinfo u1 = userMapper.selectOne(new QueryWrapper<Userinfo>().eq("uid", user.getUid()));
        if (u1 == null || u1.getUid() == null || PasswordUtils.decrypt(user.getPassword(),u1.getPassword())) {
            return ResultAjax.fail(2, "账号或密码错误");
        }

        HttpSession session = req.getSession();
        session.setAttribute(AppVarible.SESSION_USERINFO_KEY, u1);
        return ResultAjax.fail(200, "登陆成功");
    }
    //    退出
    @PostMapping("logout")
    public ResultAjax logout(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute(AppVarible.SESSION_USERINFO_KEY) != null) {
            session.removeAttribute(AppVarible.SESSION_USERINFO_KEY);
        }
        return ResultAjax.succ(1);
    }

    //修改个人信息
    @PostMapping("upInfo")
    public ResultAjax upInfo(HttpServletRequest req,String uName,String url){
        Userinfo user = SessionUtils.getUser(req);
        if(user == null){
            return ResultAjax.fail(-1,"非法");
        }
        user.setUname(uName);
        user.setUrl(url);
        HttpSession session = req.getSession();
        session.setAttribute(AppVarible.SESSION_USERINFO_KEY, user);
        if(userService.saveOrUpdate(user)){
            return ResultAjax.succ("修改成功");
        }
        return ResultAjax.fail(-1,"修改失败");
    }

    //照片上传功能-假
    @RequestMapping("/upload")
    public ResultAjax upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        Userinfo user= SessionUtils.getUser(request);
        if(user==null){
            return ResultAjax.fail(-1,"非法请求");
        }
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String dirPath = jarF.getParentFile().toString() + "/photo/";
        File filePath = new File(dirPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        //获取文件名
       // String oldname = multipartFile.getOriginalFilename();

        //构建图片名并且保存在指定目录
        String newName=user.getUid()+".jpg";
        user.setPhoto(newName);
        userService.saveOrUpdate(user);
        try {
            File existingFile = new File(dirPath, newName);
            if (existingFile.exists()) {
                // 如果存在同名文件，先删除
                existingFile.delete();
            }
            Path filePath2 = Paths.get(dirPath, newName);
            Files.copy( multipartFile.getInputStream(),filePath2, StandardCopyOption.REPLACE_EXISTING);
        }catch (IOException e){
            e.printStackTrace();
           return ResultAjax.fail(-1,"上传失败");
        }
        return ResultAjax.succ(200);
    }
    //获取头像路径-假
    @PostMapping ("/log")
    public ResultAjax log(HttpServletRequest request){
        Userinfo user= SessionUtils.getUser(request);
        if(user==null || user.getPhoto().equals("./img/logo2.jpg")){
            return ResultAjax.fail(-1,"请求失败");
        }
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String dirPath = jarF.getParentFile().toString() + "\\photo\\";
        File filePath = new File(dirPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        String imageUrl=dirPath+userService.getUser(user.getUid()).getPhoto();
        return ResultAjax.succ(imageUrl);
    }

    //直接获取图片流-假
    @GetMapping("/get-image")
    public ResponseEntity<byte[]> getImage(HttpServletRequest request) throws IOException {
        Userinfo user= SessionUtils.getUser(request);
        String str=user.getUid();

        ClassLoader imageResource = getClass().getClassLoader();

        URL url = imageResource.getResource("photo/"+str+".jpg");
        if (url == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        try (InputStream imageStream = imageResource.getResourceAsStream( "photo/"+str+".jpg")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            while ((bytesRead = imageStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            byte[] imageBytes = outputStream.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);

            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        }
    }

    //修改密码
    @RequestMapping("changePassword")
    public ResultAjax changePassword(HttpServletRequest req,String password1,String password2,String password3){
        Userinfo user=SessionUtils.getUser(req);
        if(PasswordUtils.decrypt(password1,user.getPassword())){
            return ResultAjax.fail(-1,"密码错误");
        }
        if(user==null || !password2.equals(password3)){
            return ResultAjax.fail(-1,"非法请求");
        }

        String newPassword= PasswordUtils.encrypt(password2);
        int num = userService.changepd(user.getUid(), newPassword);
        user.setPassword(newPassword);
        HttpSession session = req.getSession();
        session.setAttribute(AppVarible.SESSION_USERINFO_KEY, user);
        return ResultAjax.succ(200, "修改成功");

    }
}
